<?php
namespace app\model\mysql;

use think\Model;

class Product extends Model {

    protected $name = "product";

    protected $hidden = ["is_delete"];

    protected $autoWriteTimestamp = true;

    protected $createTime = "created_time";

    protected $updateTime = "updated_time";


    public function pageList($paginate, $where, $order, $fields) {
        if (empty($paginate)) {
            return [];
        }
        $model = $this;
        $model = $model->where("is_delete",  0);
        if (!empty($where)) {
            $model = $model->withSearch(array_keys($where), $where);
        }
        if (!empty($order)) {
            $model = $model->order($order);
        }
        if (!empty($fields)) {
            $model = $model->field($fields);
        }
        return $model->paginate($paginate);
    }

    public function searchBigImgAttr($model, $value = "", $data = [], $prefix = "") {
        if ($value == "<>") {
            $model->whereRaw("big_img <> '' OR big_img IS NOT NULL");
        }
        return $model;
    }

    public function recommendGoods($pageSize = 6, $fields = "") {
        $where = [
            "is_delete" => 0,
            "is_home_recommend" => 1,
        ];
        $order = [
            "id" => "DESC"
        ];
        $model = $this;
        if ($fields != "") {
            $model = $model->field($fields);
        }
        $result = $model->where($where)->limit($pageSize)->order($order)->select();

        return $result->toArray();
    }

    public function search($data) : array {
        $model = $this;
        if (isset($data["order"])) {
            $model = $model->order($data["order"]);
        }
        if (isset($data["where"])) {
            $model = $model->where($data["where"]);
        }
        if (isset($data["FIND_IN_SET"])) {
            $model = $model->whereFindInSet($data["FIND_IN_SET"][0], $data["FIND_IN_SET"][1]);
        }
        if (isset($data["field"])) {
            $model = $model->field($data["field"]);
        }

        $result = $model->paginate([
            "list_rows" => $data["pageSize"],
            "page" => $data["page"]
        ]);

        return $result->toArray();

    }

}